﻿using JinYuan.Models;
using Newtonsoft.Json;
using PLCCommunication.MQTT;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace JinYuan.Helper
{
    public class MqttService : IDisposable
    {
        private readonly MqttClient _mqttClient;
        private readonly object _syncLock = new object();
        private readonly MqttConfig _config;
        public class MqttConfig
        {
            public string ServerAddress { get; set; } = "10.22.161.1";
            public int ServerPort { get; set; } = 2883;
            public string ClientId { get; set; } = "601PWM01";
            //进出站主题
            public string TopicInOut { get; set; } = "EVE/60J/TrackInOut/601PWM01";
            //预测性维护数据主题
            public string TopicForecast { get; set; } = "EVE/60J/EQP/601PWM01";
            // 其他配置项...
        }

        public MqttService(MqttConfig config)
        {
            _config = config;
            _mqttClient = new MqttClient(new MqttConnectionOptions
            {
                ClientId = _config.ClientId,
                IpAddress = _config.ServerAddress,
                Port = _config.ServerPort,
                Credentials = new MqttCredential("", "") // 无用户名密码
            });
            InitializeConnection();
            StartHeartbeat();//心跳检测
        }

        #region 长连接
        /// <summary>
        /// 初始化长连接
        /// </summary>
        private void InitializeConnection()
        {
            lock (_syncLock)
            {
                if (_mqttClient.IsConnected) return;
                var result = _mqttClient.ConnectServer();
                if (result.IsSuccess)
                {
                    Logger.WriteMqtt("MQTT 长连接建立成功");
                    // 订阅需要的主题
                    SubscribeTopics();
                }
                else
                {
                    Logger.WriteMqtt($"MQTT 长连接建立失败: {result.Message}");
                }
            }
        }
        /// <summary>
        /// 订阅主题
        /// </summary>
        private void SubscribeTopics()
        {
            //_mqttClient.OnMqttMessageReceived += MqttMessageReceived;

            var topics = new[] { _config.TopicInOut, _config.TopicForecast };
            foreach (var topic in topics)
            {
                var result = _mqttClient.SubscribeMessage(topic);
                if (result.IsSuccess)
                {
                    Logger.WriteMqtt($"订阅主题成功: {topic}");
                }
                else
                {
                    Logger.WriteMqtt($"订阅主题失败: {topic}, 错误: {result.Message}");
                }
            }
        }

        /// <summary>
        /// 消息接收处理
        /// </summary>
        /// <param name="client"></param>
        /// <param name="message"></param>
        private void MqttMessageReceived(MqttClient client, MqttApplicationMessage message)
        {
            Logger.WriteMqtt($"收到消息: 主题[{message.Topic}], 内容[{Encoding.UTF8.GetString(message.Payload)}]");
        }
        #endregion

        #region 发送消息
        /// <summary>
        /// 发送进出站消息
        /// </summary>
        /// <param name="action"></param>
        public void SendInOutMessage(string action)
        {
            try
            {
                lock (_syncLock)
                {
                    if (!_mqttClient.IsConnected)
                        Reconnect();

                    var message = BuildInOutMessage(action);
                    var result = _mqttClient.PublishMessage(new MqttApplicationMessage
                    {
                        Topic = _config.TopicInOut,
                        Payload = Encoding.UTF8.GetBytes(message),
                        QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
                        Retain = false
                    });

                    if (result.IsSuccess)
                    {
                        Logger.WriteMqtt($"进出站消息发送成功 主题：{_config.TopicInOut}: {message}");
                    }
                    else
                    {
                        Logger.WriteError($"进出站消息发送失败: {result.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError($"发送进出站消息异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 发送预测数据
        /// </summary>
        /// <param name="data"></param>
        public void SendForecastMessage(Predictability_BM data)
        {
            try
            {
                lock (_syncLock)
                {
                    if (!_mqttClient.IsConnected)
                    {
                        Reconnect();
                    }

                    var message = BuildForecastMessage(data);
                    var result = _mqttClient.PublishMessage(new MqttApplicationMessage
                    {
                        Topic = _config.TopicForecast,
                        Payload = Encoding.UTF8.GetBytes(message),
                        QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
                        Retain = false
                    });

                    if (result.IsSuccess)
                    {
                        Logger.WriteInfo($"预测数据发送成功 主题：{_config.TopicForecast}: {message}");
                    }
                    else
                    {
                        Logger.WriteError($"预测数据发送失败: {result.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError($"发送预测数据异常: {ex.Message}", ex);
            }
        }


        #endregion

        #region 构建消息
        /// <summary>
        /// 构建进出站消息
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        private string BuildInOutMessage(string action)
        {
            try
            {
                var message = new EnterandExit
                {
                    bu_id = "EVE8BU",
                    district_id = "JM",
                    factory_id = "60J",
                    production_line_id = "601L",
                    work_center_id = "601PWE01",
                    device_name = "601PWM01",
                    action = action,
                    action_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                };

                return JsonConvert.SerializeObject(message, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = Formatting.None
                });
            }
            catch (Exception ex)
            {
                Logger.WriteError($"构建进出站消息失败: {ex.Message}", ex);
                return string.Empty;
            }
        }

        /// <summary>
        /// 构建预测数据消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string BuildForecastMessage(Predictability_BM predictability)
        {
            try
            {
                CollectionUpload collectionUpload = new CollectionUpload()
                {
                    bu_id = "EVE8BU",
                    district_id = "JM",
                    factory_id = "60J",
                    production_line_id = "601L",
                    production_processes_id = "",
                    work_center_id = "601PWE01",
                    station_id = "",
                    device_name = "601PWM01",
                    taglist = new List<Collection>
                    {
                        new Collection
                        {
                            device_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            collection_items = new Dictionary<string, string>
                            {
                                //扭矩
                                {"Coating1_Torque1", predictability.Coating1_Torque1},
                                {"Coating1_Torque2", predictability.Coating1_Torque2},
                                {"Coating1_Torque3", predictability.Coating1_Torque3},
                                {"Coating1_Torque4", predictability.Coating1_Torque4},
                                {"Coating1_Torque5", predictability.Coating1_Torque5},
                                {"Coating1_Torque6", predictability.Coating1_Torque6},
                                {"Coating1_Torque7", predictability.Coating1_Torque7},
                                {"Coating1_Torque8", predictability.Coating1_Torque8},
                                {"Coating2_Torque1", predictability.Coating2_Torque1},
                                {"Coating2_Torque2", predictability.Coating2_Torque2},
                                {"Coating2_Torque3", predictability.Coating2_Torque3},
                                {"Coating2_Torque4", predictability.Coating2_Torque4},
                                {"Coating2_Torque5", predictability.Coating2_Torque5},
                                {"Coating2_Torque6", predictability.Coating2_Torque6},
                                {"Coating2_Torque7", predictability.Coating2_Torque7},
                                {"Coating2_Torque8", predictability.Coating2_Torque8},
                                {"Folding1_Torque1", predictability.Folding1_Torque1},
                                {"Folding1_Torque2", predictability.Folding1_Torque2},
                                {"Folding1_Torque3", predictability.Folding1_Torque3},
                                {"Folding2_Torque1", predictability.Folding2_Torque1},
                                {"Folding2_Torque2", predictability.Folding2_Torque2},
                                {"Folding2_Torque3", predictability.Folding2_Torque3},
                                //轴速度
                                {"Coating1_AxisSpeed1", predictability.Coating1_AxisSpeed1},
                                {"Coating1_AxisSpeed2", predictability.Coating1_AxisSpeed2},
                                {"Coating1_AxisSpeed3", predictability.Coating1_AxisSpeed3},
                                {"Coating1_AxisSpeed4", predictability.Coating1_AxisSpeed4},
                                {"Coating1_AxisSpeed5", predictability.Coating1_AxisSpeed5},
                                {"Coating1_AxisSpeed6", predictability.Coating1_AxisSpeed6},
                                {"Coating1_AxisSpeed7", predictability.Coating1_AxisSpeed7},
                                {"Coating1_AxisSpeed8", predictability.Coating1_AxisSpeed8},
                                {"Coating2_AxisSpeed1", predictability.Coating2_AxisSpeed1},
                                {"Coating2_AxisSpeed2", predictability.Coating2_AxisSpeed2},
                                {"Coating2_AxisSpeed3", predictability.Coating2_AxisSpeed3},
                                {"Coating2_AxisSpeed4", predictability.Coating2_AxisSpeed4},
                                {"Coating2_AxisSpeed5", predictability.Coating2_AxisSpeed5},
                                {"Coating2_AxisSpeed6", predictability.Coating2_AxisSpeed6},
                                {"Coating2_AxisSpeed7", predictability.Coating2_AxisSpeed7},
                                {"Coating2_AxisSpeed8", predictability.Coating2_AxisSpeed8},
                                {"Folding1_AxisSpeed1", predictability.Folding1_AxisSpeed1},
                                {"Folding1_AxisSpeed2", predictability.Folding1_AxisSpeed2},
                                {"Folding1_AxisSpeed3", predictability.Folding1_AxisSpeed3},
                                {"Folding2_AxisSpeed1", predictability.Folding2_AxisSpeed1},
                                {"Folding2_AxisSpeed2", predictability.Folding2_AxisSpeed2},
                                {"Folding2_AxisSpeed3", predictability.Folding2_AxisSpeed3},
                                //轴位置
                                {"Coating1_AxisPosition1", predictability.Coating1_AxisPosition1},
                                {"Coating1_AxisPosition2", predictability.Coating1_AxisPosition2},
                                {"Coating1_AxisPosition3", predictability.Coating1_AxisPosition3},
                                {"Coating1_AxisPosition4", predictability.Coating1_AxisPosition4},
                                {"Coating1_AxisPosition5", predictability.Coating1_AxisPosition5},
                                {"Coating1_AxisPosition6", predictability.Coating1_AxisPosition6},
                                {"Coating1_AxisPosition7", predictability.Coating1_AxisPosition7},
                                {"Coating1_AxisPosition8", predictability.Coating1_AxisPosition8},
                                {"Coating2_AxisPosition1", predictability.Coating2_AxisPosition1},
                                {"Coating2_AxisPosition2", predictability.Coating2_AxisPosition2},
                                {"Coating2_AxisPosition3", predictability.Coating2_AxisPosition3},
                                {"Coating2_AxisPosition4", predictability.Coating2_AxisPosition4},
                                {"Coating2_AxisPosition5", predictability.Coating2_AxisPosition5},
                                {"Coating2_AxisPosition6", predictability.Coating2_AxisPosition6},
                                {"Coating2_AxisPosition7", predictability.Coating2_AxisPosition7},
                                {"Coating2_AxisPosition8", predictability.Coating2_AxisPosition8},
                                {"Folding1_AxisPosition1", predictability.Folding1_AxisPosition1},
                                {"Folding1_AxisPosition2", predictability.Folding1_AxisPosition2},
                                {"Folding1_AxisPosition3", predictability.Folding1_AxisPosition3},
                                {"Folding2_AxisPosition1", predictability.Folding2_AxisPosition1},
                                {"Folding2_AxisPosition2", predictability.Folding2_AxisPosition2},
                                {"Folding2_AxisPosition3", predictability.Folding2_AxisPosition3},
                                //行程时间
                                {"Coating1_Cylinder_TravelTime1", predictability.Coating1_Cylinder_TravelTime1},
                                {"Coating1_Cylinder_TravelTime2", predictability.Coating1_Cylinder_TravelTime2},
                                {"Coating1_Cylinder_TravelTime3", predictability.Coating1_Cylinder_TravelTime3},
                                {"Coating1_Cylinder_TravelTime4", predictability.Coating1_Cylinder_TravelTime4},
                                {"Coating1_Cylinder_TravelTime5", predictability.Coating1_Cylinder_TravelTime5},
                                {"Coating1_Cylinder_TravelTime6", predictability.Coating1_Cylinder_TravelTime6},
                                {"Coating1_Cylinder_TravelTime7", predictability.Coating1_Cylinder_TravelTime7},
                                {"Coating1_Cylinder_TravelTime8", predictability.Coating1_Cylinder_TravelTime8},
                                {"Coating1_Cylinder_TravelTime9", predictability.Coating1_Cylinder_TravelTime9},
                                {"Coating1_Cylinder_TravelTime10", predictability.Coating1_Cylinder_TravelTime10},
                                {"Coating1_Cylinder_TravelTime11", predictability.Coating1_Cylinder_TravelTime11},
                                {"Coating1_Cylinder_TravelTime12", predictability.Coating1_Cylinder_TravelTime12},
                                {"Coating1_Cylinder_TravelTime13", predictability.Coating1_Cylinder_TravelTime13},
                                {"Coating1_Cylinder_TravelTime14", predictability.Coating1_Cylinder_TravelTime14},
                                {"Coating2_Cylinder_TravelTime1", predictability.Coating2_Cylinder_TravelTime1},
                                {"Coating2_Cylinder_TravelTime2", predictability.Coating2_Cylinder_TravelTime2},
                                {"Coating2_Cylinder_TravelTime3", predictability.Coating2_Cylinder_TravelTime3},
                                {"Coating2_Cylinder_TravelTime4", predictability.Coating2_Cylinder_TravelTime4},
                                {"Coating2_Cylinder_TravelTime5", predictability.Coating2_Cylinder_TravelTime5},
                                {"Coating2_Cylinder_TravelTime6", predictability.Coating2_Cylinder_TravelTime6},
                                {"Coating2_Cylinder_TravelTime7", predictability.Coating2_Cylinder_TravelTime7},
                                {"Coating2_Cylinder_TravelTime8", predictability.Coating2_Cylinder_TravelTime8},
                                {"Coating2_Cylinder_TravelTime9", predictability.Coating2_Cylinder_TravelTime9},
                                {"Coating2_Cylinder_TravelTime10", predictability.Coating2_Cylinder_TravelTime10},
                                {"Coating2_Cylinder_TravelTime11", predictability.Coating2_Cylinder_TravelTime11},
                                {"Coating2_Cylinder_TravelTime12", predictability.Coating2_Cylinder_TravelTime12},
                                {"Coating2_Cylinder_TravelTime13", predictability.Coating2_Cylinder_TravelTime13},
                                {"Coating2_Cylinder_TravelTime14", predictability.Coating2_Cylinder_TravelTime14},
                                {"CornerCutting1_Cylinder_TravelTime1", predictability.CornerCutting1_Cylinder_TravelTime1},
                                {"CornerCutting1_Cylinder_TravelTime2", predictability.CornerCutting1_Cylinder_TravelTime2},
                                {"CornerCutting1_Cylinder_TravelTime3", predictability.CornerCutting1_Cylinder_TravelTime3},
                                {"CornerCutting1_Cylinder_TravelTime4", predictability.CornerCutting1_Cylinder_TravelTime4},
                                {"CornerCutting1_Cylinder_TravelTime5", predictability.CornerCutting1_Cylinder_TravelTime5},
                                {"CornerCutting1_Cylinder_TravelTime6", predictability.CornerCutting1_Cylinder_TravelTime6},
                                {"CornerCutting1_Cylinder_TravelTime7", predictability.CornerCutting1_Cylinder_TravelTime7},
                                {"CornerCutting1_Cylinder_TravelTime8", predictability.CornerCutting1_Cylinder_TravelTime8},
                                {"CornerCutting2_Cylinder_TravelTime1", predictability.CornerCutting2_Cylinder_TravelTime1},
                                {"CornerCutting2_Cylinder_TravelTime2", predictability.CornerCutting2_Cylinder_TravelTime2},
                                {"CornerCutting2_Cylinder_TravelTime3", predictability.CornerCutting2_Cylinder_TravelTime3},
                                {"CornerCutting2_Cylinder_TravelTime4", predictability.CornerCutting2_Cylinder_TravelTime4},
                                {"CornerCutting2_Cylinder_TravelTime5", predictability.CornerCutting2_Cylinder_TravelTime5},
                                {"CornerCutting2_Cylinder_TravelTime6", predictability.CornerCutting2_Cylinder_TravelTime6},
                                {"CornerCutting2_Cylinder_TravelTime7", predictability.CornerCutting2_Cylinder_TravelTime7},
                                {"CornerCutting2_Cylinder_TravelTime8", predictability.CornerCutting2_Cylinder_TravelTime8},
                            }
                        }
                }
                };
                // 根据实际数据结构调整
                return JsonConvert.SerializeObject(collectionUpload, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = Formatting.None
                });
            }
            catch (Exception ex)
            {
                Logger.WriteError($"构建预测数据消息失败: {ex.Message}", ex);
                return string.Empty;
            }
        }
        #endregion

        /// <summary>
        /// 重新连接
        /// </summary>
        private void Reconnect()
        {
            try
            {
                _mqttClient.ConnectClose();
                InitializeConnection();
            }
            catch (Exception ex)
            {
                Logger.WriteError($"MQTT重连失败: {ex.Message}", ex);
            }
        }
        #region 资源释放跟心跳检测
        private Timer _heartbeatTimer;
        private bool _disposed = false;


        // 心跳检测
        private void StartHeartbeat()
        {
            _heartbeatTimer = new Timer(state =>
            {
                try
                {
                    if (!_mqttClient.IsConnected)
                    {
                        Logger.WriteMqtt("检测到MQTT连接断开，尝试重连...");
                        Reconnect();
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError($"心跳检测异常: {ex.Message}", ex);
                }
            }, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); // 每分钟检查一次
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;

            if (disposing)
            {
                _heartbeatTimer?.Dispose();
                _mqttClient?.ConnectClose();
                _mqttClient?.Dispose();
            }

            _disposed = true;
        }

        ~MqttService()
        {
            Dispose(false);
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
    /*public class SendDateMQTT
    {
        HslCommunication.MQTT.MqttClient mqttClientIN = null;
        HslCommunication.MQTT.MqttClient mqttClientOUT = null;
        HslCommunication.MQTT.MqttClient mqttClientForecast = null;
        private static readonly object ObjectIN = new object();
        private static readonly object ObjectOUT = new object();
        private static readonly object ObjectForecast = new object();
        //10.22.160.144
        public string MQTTServerAddress = "10.22.161.1";//"10.22.161.1";
        public int MQTTServerPort = 2883;//2883
        public string ClientId = "601PWM01";

        /// <summary> 进出站主题</summary>
        public string Topic = "EVE/60J/TrackInOut/601PWM01";
        /// <summary>CTPCTQ主题</summary>
        public string Topic1 = "EVE/60J/CTPCTQ/601PWM01";
        // <summary>预测性维护数据主题</summary>
        public string Topic2 = "EVE/60J/EQP/601PWM01";

        /// <summary>BU编码</summary>
        public string BU_id = "EVE8BU";
        /// <summary>区域简称</summary>
        public string District_id = "JM";
        /// <summary>工厂编码</summary>
        public string Factory_id = "60J";
        /// <summary>工序编码</summary>
        public string Production_line_id = "601L";
        /// <summary>工作中心编码</summary>
        public string Work_center_id = "601PWE01";
        /// <summary>设备编码</summary>
        public string Device_name = "601PWM01";

        /// <summary>
        /// 发送Mqtt进站数据
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="IP"></param>
        /// <param name="Port"></param>
        /// <param name="cTPCTQDate"></param>
        public void EnterandExitSendMessgeIN()
        {
            try
            {

                lock (ObjectIN)
                {
                    if (mqttClientIN != null) { mqttClientIN.ConnectClose(); }
                    Connect(mqttClientIN, MQTTServerAddress, MQTTServerPort, "", "");
                    SubscribeMessage(mqttClientIN, Topic);
                    PublishMessage(mqttClientIN, Topic, EnterandExitMessge("0"));
                }



            }
            catch (Exception ex)
            {
                Logger.WriteError($"发送进出站数据错误，{ex.Message}", ex);
                //CommonMethods.AddLog(true, $"发送进出站数据错误，{ex.Message}");
            }
        }
        /// <summary>
        /// 发送Mqtt出站数据
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="IP"></param>
        /// <param name="Port"></param>
        /// <param name="cTPCTQDate"></param>
        public void EnterandExitSendMessgeOUT()
        {
            try
            {

                lock (ObjectOUT)
                {
                    if (mqttClientOUT != null) { mqttClientOUT.ConnectClose(); }
                    Connect(mqttClientOUT, MQTTServerAddress, MQTTServerPort, "", "");
                    SubscribeMessage(mqttClientOUT, Topic);
                    PublishMessage(mqttClientOUT, Topic, EnterandExitMessge("1"));
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError($"发送进出站数据错误，{ex.Message}", ex);
                //CommonMethods.AddLog(true, $"发送进出站数据错误，{ex.Message}");
            }
        }
        /// <summary>
        /// 发送采集项数据
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="IP"></param>
        /// <param name="Port"></param>
        /// <param name="预测性维护数据"></param>
        public void CollectionSendMessgeForecast(Predictability_BM predictability)
        {
            try
            {

                lock (ObjectForecast)
                {
                    if (mqttClientForecast != null) { mqttClientForecast.ConnectClose(); }
                    Connect(mqttClientForecast, MQTTServerAddress, MQTTServerPort, "", "");
                    SubscribeMessage(mqttClientForecast, Topic2);
                    PublishMessage(mqttClientForecast, Topic2, CollectionMessge(predictability));
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError($"发送采集项数据错误，{ex.Message}", ex);
                //CommonMethods.AddLog(false, $"发送采集项数据错误，{ex.Message}");
            }
        }

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="clientId"></param>
        public void Connect(MqttClient mqttClient, string ip, int port, string name, string pwd, string clientId = "ClientId")
        {
            try
            {
                if (mqttClient != null) mqttClient.ConnectClose();

                mqttClient = new MqttClient(new MqttConnectionOptions()
                {
                    ClientId = clientId,
                    IpAddress = ip,
                    Port = port,
                    Credentials = new MqttCredential(name, pwd),   // 设置了用户名和密码
                });

                OperateResult connect = mqttClient.ConnectServer();
                if (connect.IsSuccess)
                {
                    Logger.WriteMqtt("MQTT 连接服务器成功");
                }
                else
                {
                    Logger.WriteMqtt("MQTT 无法连接到服务器");
                }

            }
            catch (Exception ex)
            {
                Logger.WriteError($"MQTT 无法连接到服务器: {ex.Message}");
            }


        }

        /// <summary>
        /// 发布信息
        /// </summary>
        /// <param name="topic"></param>
        public void PublishMessage(MqttClient mqttClient, string topic, string Message)
        {
            try
            {

                OperateResult result = mqttClient.PublishMessage(new MqttApplicationMessage()
                {
                    Topic = topic,                                                    // 主题
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,     // 消息等级
                    Payload = Encoding.UTF8.GetBytes(Message),                        // 数据
                    Retain = false,                                                   // 是否保留
                });
                if (result.IsSuccess)
                {
                    Logger.WriteMqtt($"发送消息到主题 [{topic}]: {Message}");
                }
                else
                {
                    Logger.WriteMqtt($"发送消息到主题 [{topic}] 失败: {result.Message}");
                }

            }
            catch (Exception ex)
            {
                Logger.WriteError($"MQTT 无法连接到服务器: {ex.Message}");
            }
        }

        /// <summary>
        /// 订阅主题
        /// </summary>
        /// <param name="topic"></param>
        public void SubscribeMessage(MqttClient mqttClient, string Topic)
        {
            try
            {

                mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived; // 调用一次即可
                OperateResult Result = mqttClient.SubscribeMessage(Topic);     // 订阅A的主题
                if (Result.IsSuccess)
                {
                    Logger.WriteMqtt($"订阅成功[{Topic}]");
                }
                else
                {
                    Logger.WriteMqtt($"订阅失败[{Topic}]");
                }

            }
            catch (Exception ex)
            {
                Logger.WriteError($"订阅失败[{ex.Message}]");
            }
        }

        private static void MqttClient_OnMqttMessageReceived(MqttClient client, MqttApplicationMessage message)
        {
            Logger.WriteMqtt($"收到服务器信息[{message.ToString()}]");
        }

        /// <summary>
        /// 拼接进出站json
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public string EnterandExitMessge(string action)
        {
            string messgeJson = string.Empty;
            try
            {
                EnterandExit enterandExit = new EnterandExit()
                {
                    bu_id = BU_id,
                    district_id = District_id,
                    factory_id = Factory_id,
                    production_line_id = Production_line_id,
                    production_processes_id = "",
                    work_center_id = Work_center_id,
                    station_id = "",
                    device_name = Device_name,
                    action = action,
                    action_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),

                };
                var messageJson = JsonConvert.SerializeObject(enterandExit, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = Formatting.None
                });
                messgeJson = messageJson;
            }
            catch (Exception ex)
            {
                Logger.WriteError($"方法：上传MQTTServer数据，上传失败: {ex.Message}", ex);
            }
            return messgeJson;
        }

        /// <summary>
        /// 拼接采集项数据
        /// </summary>
        /// <param name="cPQCPTDate"></param>
        /// <returns></returns>
        public string CollectionMessge(Predictability_BM predictability)
        {
            string messgejson = string.Empty;
            try
            {
                CollectionUpload collectionUpload = new CollectionUpload()
                {
                    bu_id = BU_id,
                    district_id = District_id,
                    factory_id = Factory_id,
                    production_line_id = Production_line_id,
                    production_processes_id = "",
                    work_center_id = Work_center_id,
                    station_id = "",
                    device_name = Device_name,
                    taglist = new List<Collection>
                    {
                        new Collection
                        {
                            device_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            collection_items = new Dictionary<string, string>
                            {
                                //扭矩
                                {"Coating1_Torque1", predictability.Coating1_Torque1},
                                {"Coating1_Torque2", predictability.Coating1_Torque2},
                                {"Coating1_Torque3", predictability.Coating1_Torque3},
                                {"Coating1_Torque4", predictability.Coating1_Torque4},
                                {"Coating1_Torque5", predictability.Coating1_Torque5},
                                {"Coating1_Torque6", predictability.Coating1_Torque6},
                                {"Coating1_Torque7", predictability.Coating1_Torque7},
                                {"Coating1_Torque8", predictability.Coating1_Torque8},
                                {"Coating2_Torque1", predictability.Coating2_Torque1},
                                {"Coating2_Torque2", predictability.Coating2_Torque2},
                                {"Coating2_Torque3", predictability.Coating2_Torque3},
                                {"Coating2_Torque4", predictability.Coating2_Torque4},
                                {"Coating2_Torque5", predictability.Coating2_Torque5},
                                {"Coating2_Torque6", predictability.Coating2_Torque6},
                                {"Coating2_Torque7", predictability.Coating2_Torque7},
                                {"Coating2_Torque8", predictability.Coating2_Torque8},
                                {"Folding1_Torque1", predictability.Folding1_Torque1},
                                {"Folding1_Torque2", predictability.Folding1_Torque2},
                                {"Folding1_Torque3", predictability.Folding1_Torque3},
                                {"Folding2_Torque1", predictability.Folding2_Torque1},
                                {"Folding2_Torque2", predictability.Folding2_Torque2},
                                {"Folding2_Torque3", predictability.Folding2_Torque3},
                                //轴速度
                                {"Coating1_AxisSpeed1", predictability.Coating1_AxisSpeed1},
                                {"Coating1_AxisSpeed2", predictability.Coating1_AxisSpeed2},
                                {"Coating1_AxisSpeed3", predictability.Coating1_AxisSpeed3},
                                {"Coating1_AxisSpeed4", predictability.Coating1_AxisSpeed4},
                                {"Coating1_AxisSpeed5", predictability.Coating1_AxisSpeed5},
                                {"Coating1_AxisSpeed6", predictability.Coating1_AxisSpeed6},
                                {"Coating1_AxisSpeed7", predictability.Coating1_AxisSpeed7},
                                {"Coating1_AxisSpeed8", predictability.Coating1_AxisSpeed8},
                                {"Coating2_AxisSpeed1", predictability.Coating2_AxisSpeed1},
                                {"Coating2_AxisSpeed2", predictability.Coating2_AxisSpeed2},
                                {"Coating2_AxisSpeed3", predictability.Coating2_AxisSpeed3},
                                {"Coating2_AxisSpeed4", predictability.Coating2_AxisSpeed4},
                                {"Coating2_AxisSpeed5", predictability.Coating2_AxisSpeed5},
                                {"Coating2_AxisSpeed6", predictability.Coating2_AxisSpeed6},
                                {"Coating2_AxisSpeed7", predictability.Coating2_AxisSpeed7},
                                {"Coating2_AxisSpeed8", predictability.Coating2_AxisSpeed8},
                                {"Folding1_AxisSpeed1", predictability.Folding1_AxisSpeed1},
                                {"Folding1_AxisSpeed2", predictability.Folding1_AxisSpeed2},
                                {"Folding1_AxisSpeed3", predictability.Folding1_AxisSpeed3},
                                {"Folding2_AxisSpeed1", predictability.Folding2_AxisSpeed1},
                                {"Folding2_AxisSpeed2", predictability.Folding2_AxisSpeed2},
                                {"Folding2_AxisSpeed3", predictability.Folding2_AxisSpeed3},
                                //轴位置
                                {"Coating1_AxisPosition1", predictability.Coating1_AxisPosition1},
                                {"Coating1_AxisPosition2", predictability.Coating1_AxisPosition2},
                                {"Coating1_AxisPosition3", predictability.Coating1_AxisPosition3},
                                {"Coating1_AxisPosition4", predictability.Coating1_AxisPosition4},
                                {"Coating1_AxisPosition5", predictability.Coating1_AxisPosition5},
                                {"Coating1_AxisPosition6", predictability.Coating1_AxisPosition6},
                                {"Coating1_AxisPosition7", predictability.Coating1_AxisPosition7},
                                {"Coating1_AxisPosition8", predictability.Coating1_AxisPosition8},
                                {"Coating2_AxisPosition1", predictability.Coating2_AxisPosition1},
                                {"Coating2_AxisPosition2", predictability.Coating2_AxisPosition2},
                                {"Coating2_AxisPosition3", predictability.Coating2_AxisPosition3},
                                {"Coating2_AxisPosition4", predictability.Coating2_AxisPosition4},
                                {"Coating2_AxisPosition5", predictability.Coating2_AxisPosition5},
                                {"Coating2_AxisPosition6", predictability.Coating2_AxisPosition6},
                                {"Coating2_AxisPosition7", predictability.Coating2_AxisPosition7},
                                {"Coating2_AxisPosition8", predictability.Coating2_AxisPosition8},
                                {"Folding1_AxisPosition1", predictability.Folding1_AxisPosition1},
                                {"Folding1_AxisPosition2", predictability.Folding1_AxisPosition2},
                                {"Folding1_AxisPosition3", predictability.Folding1_AxisPosition3},
                                {"Folding2_AxisPosition1", predictability.Folding2_AxisPosition1},
                                {"Folding2_AxisPosition2", predictability.Folding2_AxisPosition2},
                                {"Folding2_AxisPosition3", predictability.Folding2_AxisPosition3},
                                //行程时间
                                {"Coating1_Cylinder_TravelTime1", predictability.Coating1_Cylinder_TravelTime1},
                                {"Coating1_Cylinder_TravelTime2", predictability.Coating1_Cylinder_TravelTime2},
                                {"Coating1_Cylinder_TravelTime3", predictability.Coating1_Cylinder_TravelTime3},
                                {"Coating1_Cylinder_TravelTime4", predictability.Coating1_Cylinder_TravelTime4},
                                {"Coating1_Cylinder_TravelTime5", predictability.Coating1_Cylinder_TravelTime5},
                                {"Coating1_Cylinder_TravelTime6", predictability.Coating1_Cylinder_TravelTime6},
                                {"Coating1_Cylinder_TravelTime7", predictability.Coating1_Cylinder_TravelTime7},
                                {"Coating1_Cylinder_TravelTime8", predictability.Coating1_Cylinder_TravelTime8},
                                {"Coating1_Cylinder_TravelTime9", predictability.Coating1_Cylinder_TravelTime9},
                                {"Coating1_Cylinder_TravelTime10", predictability.Coating1_Cylinder_TravelTime10},
                                {"Coating1_Cylinder_TravelTime11", predictability.Coating1_Cylinder_TravelTime11},
                                {"Coating1_Cylinder_TravelTime12", predictability.Coating1_Cylinder_TravelTime12},
                                {"Coating1_Cylinder_TravelTime13", predictability.Coating1_Cylinder_TravelTime13},
                                {"Coating1_Cylinder_TravelTime14", predictability.Coating1_Cylinder_TravelTime14},
                                {"Coating2_Cylinder_TravelTime1", predictability.Coating2_Cylinder_TravelTime1},
                                {"Coating2_Cylinder_TravelTime2", predictability.Coating2_Cylinder_TravelTime2},
                                {"Coating2_Cylinder_TravelTime3", predictability.Coating2_Cylinder_TravelTime3},
                                {"Coating2_Cylinder_TravelTime4", predictability.Coating2_Cylinder_TravelTime4},
                                {"Coating2_Cylinder_TravelTime5", predictability.Coating2_Cylinder_TravelTime5},
                                {"Coating2_Cylinder_TravelTime6", predictability.Coating2_Cylinder_TravelTime6},
                                {"Coating2_Cylinder_TravelTime7", predictability.Coating2_Cylinder_TravelTime7},
                                {"Coating2_Cylinder_TravelTime8", predictability.Coating2_Cylinder_TravelTime8},
                                {"Coating2_Cylinder_TravelTime9", predictability.Coating2_Cylinder_TravelTime9},
                                {"Coating2_Cylinder_TravelTime10", predictability.Coating2_Cylinder_TravelTime10},
                                {"Coating2_Cylinder_TravelTime11", predictability.Coating2_Cylinder_TravelTime11},
                                {"Coating2_Cylinder_TravelTime12", predictability.Coating2_Cylinder_TravelTime12},
                                {"Coating2_Cylinder_TravelTime13", predictability.Coating2_Cylinder_TravelTime13},
                                {"Coating2_Cylinder_TravelTime14", predictability.Coating2_Cylinder_TravelTime14},
                                {"CornerCutting1_Cylinder_TravelTime1", predictability.CornerCutting1_Cylinder_TravelTime1},
                                {"CornerCutting1_Cylinder_TravelTime2", predictability.CornerCutting1_Cylinder_TravelTime2},
                                {"CornerCutting1_Cylinder_TravelTime3", predictability.CornerCutting1_Cylinder_TravelTime3},
                                {"CornerCutting1_Cylinder_TravelTime4", predictability.CornerCutting1_Cylinder_TravelTime4},
                                {"CornerCutting1_Cylinder_TravelTime5", predictability.CornerCutting1_Cylinder_TravelTime5},
                                {"CornerCutting1_Cylinder_TravelTime6", predictability.CornerCutting1_Cylinder_TravelTime6},
                                {"CornerCutting1_Cylinder_TravelTime7", predictability.CornerCutting1_Cylinder_TravelTime7},
                                {"CornerCutting1_Cylinder_TravelTime8", predictability.CornerCutting1_Cylinder_TravelTime8},
                                {"CornerCutting2_Cylinder_TravelTime1", predictability.CornerCutting2_Cylinder_TravelTime1},
                                {"CornerCutting2_Cylinder_TravelTime2", predictability.CornerCutting2_Cylinder_TravelTime2},
                                {"CornerCutting2_Cylinder_TravelTime3", predictability.CornerCutting2_Cylinder_TravelTime3},
                                {"CornerCutting2_Cylinder_TravelTime4", predictability.CornerCutting2_Cylinder_TravelTime4},
                                {"CornerCutting2_Cylinder_TravelTime5", predictability.CornerCutting2_Cylinder_TravelTime5},
                                {"CornerCutting2_Cylinder_TravelTime6", predictability.CornerCutting2_Cylinder_TravelTime6},
                                {"CornerCutting2_Cylinder_TravelTime7", predictability.CornerCutting2_Cylinder_TravelTime7},
                                {"CornerCutting2_Cylinder_TravelTime8", predictability.CornerCutting2_Cylinder_TravelTime8},
                            }
                        }
                }
                };
                var messageJson = JsonConvert.SerializeObject(collectionUpload, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = Formatting.None
                });
                messgejson = messageJson;
            }
            catch (Exception ex)
            {
                Logger.WriteError($"生成Json数据失败: {ex.Message}", ex);
            }
            return messgejson;
        }
    }*/
}
